﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Configuration;
using System.Web.Security;

public partial class Admin_test : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    // 重置  
    protected void btnReset_Click(object sender, EventArgs e)
    {
        //=== 产生加密用的密码密钥 ===    
        string salt = GenerateSalt();
        Response.Write("salt:" + salt + "<br>");
        //=== 将明码密码加密(此时密码为"P@ssw0rd" 当然也可随机数生成) ===    
        string password = EncryptToHashString("123456", salt, "SHA1");
        Response.Write("password:" + password);
    }
    /// <summary>    
    /// 密码加密钥    
    /// </summary>    
    /// <returns></returns>    
    public string GenerateSalt()
    {
        byte[] data = new byte[0x10];
        new System.Security.Cryptography.RNGCryptoServiceProvider().GetBytes(data);
        return Convert.ToBase64String(data);
    }

    /// <summary>    
    /// 哈希密码加密(不可还原)    
    /// </summary>    
    /// <param name="s">原始字符串</param>    
    /// <param name="saltKey">Salt加密字符串</param>    
    /// <param name="hashName">加密格式(MD5, SHA1, SHA256, SHA384, SHA512.)</param>    
    /// <returns>加密过的密码</returns>    
    public string EncryptToHashString(string s, string saltKey, string hashName)
    {
        byte[] src = System.Text.Encoding.Unicode.GetBytes(s);
        byte[] saltbuf = Convert.FromBase64String(saltKey);
        byte[] dst = new byte[saltbuf.Length + src.Length];
        byte[] inArray = null;
        System.Buffer.BlockCopy(saltbuf, 0, dst, 0, saltbuf.Length);
        System.Buffer.BlockCopy(src, 0, dst, saltbuf.Length, src.Length);
        System.Security.Cryptography.HashAlgorithm algorithm = System.Security.Cryptography.HashAlgorithm.Create(hashName);
        inArray = algorithm.ComputeHash(dst);
        return Convert.ToBase64String(inArray);
    }
}
